document.addEventListener('DOMContentLoaded', function() {
    // 获取用户ID
    const userId = localStorage.getItem('userId');
    if (!userId) {
        alert('用户信息获取失败，请重新登录');
        window.location.href = 'login.html';
        return;
    }

    // 加载订单列表
    fetchOrders(userId);

    // 返回按钮点击事件
    document.getElementById('backBtn').addEventListener('click', function() {
        window.history.back();
    });

    // 注销按钮点击事件
    document.getElementById('logoutBtn').addEventListener('click', logout);
});

function fetchOrders(userId) {
    // 获取用户订单
    fetch(`/api/orders/user/${userId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取订单失败');
            }
            return response.json();
        })
        .then(orders => {
            const ordersList = document.getElementById('ordersList');
            ordersList.innerHTML = '';

            if (orders.length === 0) {
                ordersList.innerHTML = '<p style="text-align: center; padding: 20px;">暂无订单</p>';
                return;
            }

            orders.forEach(order => {
                const orderCard = document.createElement('div');
                orderCard.className = 'order-card';

                orderCard.innerHTML = `
                    <h3>订单编号: ${order.id}</h3>
                    <p>订单状态: ${order.status}</p>
                    <p>总价: ¥${order.totalAmount.toFixed(2)}</p>
                    <p>创建时间: ${new Date(order.createdAt).toLocaleString()}</p>
                    <div class="order-items">
                        <h4>订单商品:</h4>
                        <ul>
                            ${order.items.map(item => `
                                <li>${item.product.name} x${item.quantity} - ¥${(item.product.price * item.quantity).toFixed(2)}</li>
                            `).join('')}
                        </ul>
                    </div>
                `;

                ordersList.appendChild(orderCard);
            });
        })
        .catch(error => {
            console.error('获取订单出错:', error);
            alert('获取订单失败，请稍后再试');
        });
}

function logout() {
    // 注销登录
    localStorage.removeItem('userId');
    window.location.href = 'login.html';
}